<template>
    <div>
        <ModalComponent @open="handleOpen" modal-name="test-questions-modal" title="试题管理" :close-on-click-modal="false"
            size="1024px" type="drawer">
            <div style="padding-bottom: 16px;">
                <el-text class="mx-1" size="large">赛项：{{ info.name }}({{ info.playingTime
                }})</el-text>
            </div>
            <div class="head-btns">
                <el-space>
                    <el-button @click="handleOpenInfoModal({
                            data: {},
                            type: 'add',
                            eventId: query_data.eventId
                        })" type="primary">新建试题</el-button>
                    <el-dropdown @command="handleRemoveQuestion">
                        <el-button type="danger">删除试题</el-button>
                        <template #dropdown>
                            <el-dropdown-menu>
                                <el-dropdown-item command="all">删除全部试题</el-dropdown-item>
                                <el-dropdown-item command="select">删除所选试题</el-dropdown-item>
                            </el-dropdown-menu>
                        </template>
                    </el-dropdown>
                    <el-button @click="handleImportTestQuestion">导入试题</el-button>
                    <el-link @click="handleDownloadTpl">下载导入模版</el-link>
                </el-space>
                <el-space>
                    <el-select v-model="query_data.subjectType">
                        <el-option label="全部" value=""></el-option>
                        <el-option label="单选题" :value="1"></el-option>
                        <el-option label="主观题" :value="2"></el-option>
                        <el-option label="多选题" :value="3"></el-option>
                        <el-option label="判断题" :value="4"></el-option>
                    </el-select>
                    <el-input v-model="query_data.subjectStem" placeholder="请输入搜索内容"></el-input>
                    <el-button @click="handleLoad(true)" type="primary">搜索</el-button>
                </el-space>

            </div>
            <div>
                <el-table v-loading="loading" empty-text="暂无数据..." :data="tableData" border style="width: 100%"
                    @selection-change="handleSelectionChange">
                    <el-table-column type="selection" width="55" />
                    <el-table-column label="ID" prop="subjectId" width="100" />
                    <el-table-column label="题目" prop="stem" />
                    <el-table-column label="试题类型" prop="subjectType">
                        <template #default="scope">
                            <el-tag v-if="scope.row.subjectType == 1" type="success">单选题</el-tag>
                            <el-tag v-if="scope.row.subjectType == 2" type="warning">主观题</el-tag>
                            <el-tag v-if="scope.row.subjectType == 3" type="primary">多选题</el-tag>
                            <el-tag v-if="scope.row.subjectType == 4" type="info">判断题</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column label="正确答案" prop="correctCase" />
                    <el-table-column label="所占分数" prop="score" />
                    <el-table-column label="操作" prop="Address" width="100">
                        <template #default="scope">
                            <el-dropdown trigger="click" @command="(value) => handleOperate(value, scope.row)">
                                <span class="el_dropdown_link">
                                    操作<el-icon class="el-icon--right"><arrow-down /></el-icon>
                                </span>
                                <template #dropdown>
                                    <el-dropdown-menu>
                                        <el-dropdown-item :icon="Edit" command="edit"> 编辑试题 </el-dropdown-item>
                                        <el-dropdown-item :icon="Delete" command="del"> 删除试题 </el-dropdown-item>
                                    </el-dropdown-menu>
                                </template>
                            </el-dropdown>
                        </template>

                    </el-table-column>
                </el-table>
                <div class="pagination">
                    <el-pagination background layout="prev, pager, next, total" :total="total"
                        @current-change="handlePage" />
                </div>
            </div>
            <!-- <el-descriptions title="概览" :column="4">
                <el-descriptions-item label="单选题">1</el-descriptions-item>
                <el-descriptions-item label="单选题">2</el-descriptions-item>
                <el-descriptions-item label="单选题">3</el-descriptions-item>
                <el-descriptions-item label="单选题">4</el-descriptions-item>
            </el-descriptions> -->
            <TestQuestionsInfoModal @update="handleCloseModalAndUpdateData" />
            <el-upload ref="upload" action="#" :auto-upload="false" :show-file-list="false" :on-change="handleFileChange">
            </el-upload>
        </ModalComponent>
    </div>
</template>
<script setup >
import { onMounted, ref } from 'vue'
import ModalComponent from "@/components/modal/index.vue"
import { usePage } from "@/hooks/usePage"
import { GetSubjectList, DelSubject, DelSubjects, SubjectAdd } from '@/api/gradingTeacher';
import { ElMessage, ElMessageBox } from 'element-plus';
import TestQuestionsInfoModal from "./test-questions-info.vue"
import { open, close } from '@/utils/modal';
import { exportXlsx, readXlsx } from '@/utils/xlsx';
import { download } from '@/utils/downLoad';
const upload = ref();
// 表格数据
const {
    total: total,
    data: tableData,
    query_data,
    loading,
    handleLoad,
    handlePage
} = usePage({
    api_fn: GetSubjectList,
    q_data: {
        eventId: '',
        subjectType: "",
        subjectStem: ""
    }
})
const info = ref({})

const handleOpen = (item) => {
    console.log(item);
    info.value = item;
    query_data.value.eventId = item.eventId
    handleLoad(true);
}

const handleOperate = (command, row) => {
    if (command == 'edit') {
        // TODO 编辑弹窗
        handleOpenInfoModal({
            data: row,
            type: "edit",
            eventId: query_data.value.eventId
        });
        return;
    }
    if (command == 'del') {
        ElMessageBox.confirm('确定是否要删除该试题？', "提示", {
            "cancel-button-text": "取消",
            "confirm-button-text": "确定",
            type: "warning"
        }).then(async () => {
            let res = await DelSubject({
                subjectId: row.subjectId,
            })
            if (!res.success) {
                ElMessage.error(res.message);
            } else {
                ElMessage.success(res.message);
            }
            handleLoad(true)
        })
    }
}
const handleOpenInfoModal = (data) => {
    open('test-questions-info', data)
}
const handleCloseModalAndUpdateData = () => {
    close('test-questions-info');
    handleLoad(true)
}
/**
 * 下载导入模版
 */
const handleDownloadTpl = () => {
    download(`试题导入模版.xlsx`, "/test_question_tpl.xlsx", 'url');
}

const handleImportTestQuestion = () => {
    upload.value.$refs.uploadRef.$refs.inputRef.click()
}
const handleFileChange = async (UploadFile) => {
    console.log(UploadFile)
    console.log('change')
    const TypeArr = ["单选题", "主观题", "多选题", "判断题"]
    let data = [];
    try {
        data = await readXlsx(UploadFile.raw, '工作蒲1', (item) => {
            console.log(item)
            let obj = {
                "subjectType": TypeArr.indexOf(item['试题类型']) + 1,
                "stem": item['题干'],
                "caseA": item['选项A'] ?? "",
                "caseB": item['选项B'] ?? "",
                "caseC": item['选项C'] ?? "",
                "caseD": item['选项D'] ?? "",
                "correctCase": item['正确选项'] ?? "",
                "score": item['分数'] ?? 0,
                "imgUrl": "",
            }
            return obj
        })
    } catch (error) {
        console.log(error)
        return;
    }
    upload.value.clearFiles();
    upload.value.handleRemove(UploadFile);
    upload.value.$refs.uploadRef.$refs.inputRef.value = "";
    let res = await SubjectAdd(data, {
        eventId: query_data.value.eventId,
    })
    if (!res.success) {
        ElMessage.error(res.message);
    } else {
        ElMessage.success(res.message);
        handleLoad(true)
    }
}
const subjectIds = ref([])
const handleSelectionChange = (val) => {
    subjectIds.value = val.map((item) => item.subjectId)
}

const handleRemoveQuestion = (command) => {
    let content = command == 'all' ? '全部' : "所选";

    ElMessageBox.confirm(`确定是否要删除${content}试题？`, "提示", {
        "cancel-button-text": "取消",
        "confirm-button-text": "确定",
        type: "warning"
    }).then(async () => {
        if (command == 'select' && subjectIds.value.length == 0) {
            ElMessage.error("请选择需要删除的试题");
            return;
        }
        let res = await DelSubjects({
            subjectIds: command == 'select' ? subjectIds.value.join(',') : '-1',
            eventId: query_data.value.eventId,

        })
        if (!res.success) {
            ElMessage.error(res.message);
        } else {
            ElMessage.success(res.message);
        }
        handleLoad(true)
    })
}
onMounted(() => {
    console.log('mounted!')
})
</script>
<style lang="scss" scoped>
.el-drawer__header {
    margin: 0;
}

.head-btns {
    display: flex;
    justify-content: space-between;
    padding-bottom: 16px;
}
</style>